package com.dht.xiao.jianye.utils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.dht.xiao.jianye.R;
import com.dht.xiao.jianye.activity.UsbDoorActivity;
import com.dht.xiao.jianye.base.App;
import com.dht.xiao.jianye.base.util.CRC16Utils;
import com.licheedev.myutils.LogPlus;

import cn.wch.ch34xuartdriver.CH34xUARTDriver;

public class OpenManager {
    private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";
    private final Handler mHandler;
    private static OpenCallBack callBack;
    public interface OpenCallBack{
        void onReceiveData(String data,String command,long num ,String status);
        void onInit(Boolean data);
    }
    public void setCallBack(OpenCallBack callBack){
        this.callBack = callBack;
    }

    public OpenManager(Context context) {
        this.context  = context;
        mHandler = new Handler(Looper.getMainLooper());
        init();
    }
    
    private void init(){
        App.driver = new CH34xUARTDriver(
                (UsbManager)context.getSystemService(Context.USB_SERVICE), context,
                ACTION_USB_PERMISSION);
        if (!App.driver.UsbFeatureSupported())// 判断系统是否支持USB HOST
        {
            Dialog dialog = new AlertDialog.Builder(context)
                    .setTitle("提示")
                    .setMessage("您的手机不支持USB HOST，请更换其他手机再试！")
                    .setPositiveButton("确认",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface arg0,
                                                    int arg1) {
                                    System.exit(0);
                                }
                            }).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 保持常亮的屏幕的状态
        isOpen = false;
        open();
    }

    private Context context;
    private boolean isOpen;

    /**
     * 开锁
     */
    public void sendOpen(int num){
        StringBuilder chickLock = new StringBuilder();
        chickLock.append("574B4C59")//帧头
                .append("09")//数据字节数
                .append("01")//板地址
                .append("82")//命令标识
                .append(ByteUtil.decimal2fitHex(Integer.valueOf(num)));//开门箱

        String checkCode = ByteUtil.checkXor(chickLock.toString());
        chickLock.append(checkCode);
        sendData(chickLock.toString());
    }
    /**
     * 开锁
     */
    public void queryOpen(int num){
        StringBuilder chickLock = new StringBuilder();
        chickLock.append("574B4C59")//帧头
                .append("09")//数据字节数
                .append("01")//板地址
                .append("83")//命令标识
                .append(ByteUtil.decimal2fitHex(Integer.valueOf(num)));//开门箱

        String checkCode = ByteUtil.checkXor(chickLock.toString());
        chickLock.append(checkCode);
        sendData(chickLock.toString());
    }
    public void sendData(String data){
        byte[] to_send = ByteUtil.toByteArray(data);        //以16进制发送
        int retval = App.driver.WriteData(to_send, to_send.length);//写数据，第一个参数为需要发送的字节数组，第二个参数为需要发送的字节长度，返回实际发送的字节长度
        if (retval < 0)
            Toast.makeText(context, "Write failed!",
                    Toast.LENGTH_SHORT).show();
    }

    private int baudRate;
    private byte stopBit;
    private byte dataBit;
    private byte parity;
    private byte flowControl;


    private void open() {
        if (!isOpen) {
            int retval = App.driver.ResumeUsbPermission();
            if (retval == 0) {
                retval = App.driver.ResumeUsbList();
                if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备
                {
                    Toast.makeText(context, "Open failed!",
                            Toast.LENGTH_SHORT).show();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null){
                                callBack.onInit(false);
                            }
                        }
                    });
                    App.driver.CloseDevice();
                } else if (retval == 0) {
                    if (App.driver.mDeviceConnection != null) {
                        if (!App.driver.UartInit()) {//对串口设备进行初始化操作
                            Toast.makeText(context, "Initialization failed!",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Toast.makeText(context, "Device opened",
                                Toast.LENGTH_SHORT).show();
                        isOpen = true;

                        configData();
                        new readThread().start();//开启读线程读取串口接收的数据

                    } else {
                        Toast.makeText(context, "Open failed!",
                                Toast.LENGTH_SHORT).show();

                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (callBack != null){
                                    callBack.onInit(false);
                                }
                            }
                        });
                    }
                } else {

                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setIcon(R.drawable.ic_launcher_background);
                    builder.setTitle("未授权限");
                    builder.setMessage("确认退出吗？");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    });
                    builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub

                        }
                    });
                    builder.show();

                }
            }
        } else {
            
            isOpen = false;
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            App.driver.CloseDevice();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (callBack != null){
                        callBack.onInit(false);
                    }
                }
            });
        }

    }


    private class readThread extends Thread {

        public void run() {

            byte[] buffer = new byte[4096];

            while (true) {

                Message msg = Message.obtain();
                if (!isOpen) {
                    break;
                }
                int length = App.driver.ReadData(buffer, 4096);
                if (length > 0) {
                    String recv = ByteUtil.toHexString(buffer, length);        //以16进制输出
//					String recv = new String(buffer, 0, length);		//以字符串形式输出
                    LogPlus.e("", "获取到数据结果="+recv);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null){
                                callBack.onReceiveData(recv,recv.substring(recv.length()-10,recv.length()-8),ByteUtil.hexStr2decimal(recv.substring(recv.length()-6,recv.length()-4)),recv.substring(recv.length()-4,recv.length()-2));
                            }
                        }
                    });

                }
            }
        }
    }


    private void configData() {
        baudRate = 9600;
        stopBit = 1;
        dataBit = 8;
        parity = 0;
        flowControl = 0;
        if (App.driver.SetConfig(baudRate, dataBit, stopBit, parity,//??????????????????????????????
                flowControl)) {
            Toast.makeText(context, "Config successfully",
                    Toast.LENGTH_SHORT).show();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (callBack != null){
                        callBack.onInit(true);
                    }
                }
            });
        } else {
            Toast.makeText(context, "Config failed!",
                    Toast.LENGTH_SHORT).show();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (callBack != null){
                        callBack.onInit(false);
                    }
                }
            });
        }
    }

    public void onDestroy() {
        isOpen = false;
        App.driver.CloseDevice();
    }


}
